/*
 *	Generate the syscall functions
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "syscall_name.h"

static char namebuf[128];

static void write_call(int n)
{
  FILE *fp;
  snprintf(namebuf, 128, "fuzix6502/syscall_%s.s", syscall_name[n]);
  fp = fopen(namebuf, "w");
  if (fp == NULL) {
    perror(namebuf);
    exit(1);
  }
  fprintf(fp, "\t.export _%s\n\n", syscall_name[n]);
  fprintf(fp, "\t.import __syscall\n\n");
  fprintf(fp, "\t.import pushax\n\n");
  fprintf(fp, ".proc _%s\n", syscall_name[n]);
  if (syscall_args[n] == VARARGS) {
    /* We are not entered as fastcall, in addition y holds the argument
       count for us already. All the work is already done */
  } else {
    /* This is basically "fastcall to cdecl and set y" */
    if (syscall_args[n])
      fprintf(fp, "\tjsr pushax\n");
    fprintf(fp, "\tldy #%d\n", 2 * syscall_args[n]);
  }
  fprintf(fp, "\tldx #%d\n", n);
  fprintf(fp, "\tjmp __syscall\n\n.endproc\n");
  fclose(fp);
}

static void write_call_table(void)
{
  int i;
  for (i = 0; i < NR_SYSCALL; i++)
    write_call(i);
}

static void write_makefile(void)
{
  int i;
  FILE *fp = fopen("fuzix6502/Makefile", "w");
  if (fp == NULL) {
    perror("Makefile");
    exit(1);
  }
  fprintf(fp, "# Autogenerated by tools/syscall_6502\n");
  fprintf(fp, "AS = ca65\n");
  fprintf(fp, "AR = ar65\n");
  fprintf(fp, "ASYS = syscall.s\n");
  fprintf(fp, "ASRCS = syscall_%s.s\n", syscall_name[0]);
  for (i = 1; i < NR_SYSCALL; i++)
    fprintf(fp, "ASRCS += syscall_%s.s\n", syscall_name[i]);
  fprintf(fp, "\n\nASRCALL = $(ASRCS) $(ASYS)\n");
  fprintf(fp, "\nAOBJS = $(ASRCALL:.s=.o)\n\n");
  fprintf(fp, "../syslib.lib: $(AOBJS)\n");
  fprintf(fp, "\t$(AR) a ../syslib.lib $(AOBJS)\n\n");
  fprintf(fp, "$(AOBJS): %%.o: %%.s\n");
  fprintf(fp, "\t$(AS) -o $*.o $<\n\n");
  fprintf(fp, "\n$(ASRCS): ../../tools/syscall_6502\n");
  fprintf(fp, "\t(cd ..;../tools/syscall_6502)\n\n");
  fprintf(fp, "clean:\n");
  fprintf(fp, "\trm -f $(AOBJS) $(ASRCS) *~\n\n");
  fclose(fp);
}

int main(int argc, char *argv[])
{
  write_makefile();
  write_call_table();
  exit(0);
}
